<?


//take a stats report and export it
require "header.php";

?>
<p class="small" align="left">
Statistics > Export
</p>

<p class="heading">
Export Statitics Report
</p>
	<p>
Export monthly or quarterly reports to a csv file so you can import the data to Microsoft excel. </p>
<?
if (!$runcode)
{
	?>

	<p><u>Step 1: Select Filter</u></p>

	<p>Choose the group, status and purpose of the campaigns you would like to see and select the time period of your report using the drop down menu. If you would like to enter a custom time period, check the "use custom time" and enter the from and to date of your desired report.</p>

	<!--MAIN CONTROLS-->
	<form action=export.php method=post>
	<table width="580" border="0" cellpadding="0" cellspacing="0" align="center" valign="center">
		<tr>
			<td>Purpose</td>
			<td>Group</td>
			<td>Status</td>
			<td>Time Period</td>
		</tr>
		<tr>
			<td>
				<?
					if ($purpose == "all purposes")
						$all_purposes_selected = "selected";
					elseif ($purpose == "clicks")
						$clicks_selected = "selected";
					elseif ($purpose == "actions")
						$actions_selected = "selected";
					elseif ($purpose == "sales")
						$sales_selected = "selected";
					elseif ($purpose == "all")
						$all_selected = "selected";
					elseif ($purpose == "affiliate")
						$affiliate_selected = "selected";
				?>
				<select name="purpose" class="small">
				<option value="all purposes" <?=$all_purposes_selected?>>All</option>
				<option value="clicks" <?=$clicks_selected?>>Clicks Only</option>
				<option value="actions" <?=$actions_selected?>>Clicks & Actions</option>
				<option value="sales" <?=$sales_selected?>>Clicks & Sales</option>
				<option value="all" <?=$all_selected?>>Clicks, Actions & Sales</option>
				<option value="affiliate" <?=$affiliate_selected?>>Affiliate Link</option>
				</select>
			</td>
			<td>
				<select name="group" class="small">
				<?
					if ($group == "all")
						echo "<option value=all selected>All</option>";
					else
						echo "<option value=all>All</option>";
					if ($group == "default")
						echo "<option value=default selected>- default -</option>";
					else
						echo "<option value=default>- default -</option>";
					$groups = mysql_query("select * from adtrackz_groups order by groupname asc");
					while($group1 = mysql_fetch_row($groups))
					{
						if ($group == $group1[0])
							echo "<option value=$group1[0] selected>$group1[1]</option>";
						else
							echo "<option value=$group1[0]>$group1[1]</option>";
					}
				?>
				</select>
			</td>
			<td>
				<?
					if ($status == "all")
						$s_all_selected = "selected";
					elseif ($status == "active")
						$s_active_selected = "selected";
					elseif ($status == "ended")
						$s_ended_selected = "selected";
					elseif ($status == "pending")
						$s_pending_selected = "selected";
				?>
				<select name="status" class="small">
				<option value="all" <?=$s_all_selected?>>All</option>
				<option value="pending" <?=$s_pending_selected?>>pending</option>
				<option value="active" <?=$s_active_selected?>>active</option>
				<option value="ended" <?=$s_ended_selected?>>ended</option>
				</select> 
			</td>
			<td>
				<?
					if ($timeperiod == "all")
						$tp_all_selected = "selected";
					elseif ($timeperiod == "today")
						$tp_today_selected = "selected";
					elseif ($timeperiod == "yesterday")
						$tp_yesterday_selected = "selected";
					elseif ($timeperiod == "thisweek")
						$tp_thisweek_selected = "selected";
					elseif ($timeperiod == "lastweek")
						$tp_lastweek_selected = "selected";
					elseif ($timeperiod == "thismonth")
						$tp_thismonth_selected = "selected";
					elseif ($timeperiod == "lastmonth")
						$tp_lastmonth_selected = "selected";
					elseif ($timeperiod == "thisyear")
						$tp_thisyear_selected = "selected";
					elseif ($timeperiod == "lastyear")
						$tp_lastyear_selected = "selected";
				?>
				<select name="timeperiod" class="small">
				<option value="all" <?=$tp_all_selected?>>All Clicks</option>
				<option value="today" <?=$tp_today_selected?>>Today</option>
				<option value="yesterday" <?=$tp_yesterday_selected?>>Yesterday</option>
				<option value="thisweek" <?=$tp_thisweek_selected?>>This Week</option>
				<option value="lastweek" <?=$tp_lastweek_selected?>>Last Week</option>
				<option value="thismonth" <?=$tp_thismonth_selected?>>This Month</option>
				<option value="lastmonth" <?=$tp_lastmonth_selected?>>Last Month</option>
				<option value="thisyear" <?=$tp_thisyear_selected?>>This Year</option>
				<option value="lastyear" <?=$tp_lastyear_selected?>>Last Year</option>
				</select>
			</td>
		</tr>
	</table>
	<br>

	<!--FROM TO CONTROLS-->
	<table width="580" border="0" cellpadding="0" cellspacing="0" align="center" bordercolor="#E0E0E0">
		<tr>
			<td align="center" valign="center">
				<input type=checkbox name=submit_bottom>&nbsp;
				use custom time period	
			</td>
			<td>
				From:
				<select name="fmonth" class="small">
				<?
					if (!$fmonth)
						$thismonth = date("n");
					else
						$thismonth = $fmonth;
					$months = array(1 => 'Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
					$i=1;
					foreach ($months as $month)
					{
						if ($thismonth == $i)
							echo "<option value=\"$i\" selected>$month</option>";	
						else
							echo "<option value=\"$i\">$month</option>";
						$i++;
					}
					if (!$fday)
						$today = date("j");
					else
						$today = $fday;
					if (!$fyear)
						$thisyear = date("Y");
					else
						$thisyear = $fyear;
				?>
				</select>
				<input type="text" name="fday" class="small" size="2" value="<?=$today?>">
				<input type="text" name="fyear" class="small" size="4" value="<?=$thisyear?>">
			</td>
			<td>			
				&nbsp;&nbsp;&nbsp;&nbsp;To:
				<select name="tmonth" class="small">
				<?
					if (!$tmonth)
						$thismonth = date("n");
					else
						$thismonth = $tmonth;							
					$i=1;
					foreach ($months as $month)
					{
						if ($thismonth == $i)
							echo "<option value=\"$i\" selected>$month</option>";	
						else
							echo "<option value=\"$i\">$month</option>";
						$i++;
					}
					if (!$tday)
						$today = date("j");
					else
						$today = $tday;
					if (!$tyear)
						$thisyear = date("Y");
					else
						$thisyear = $tyear;
				?>
				</select>
				<input type="text" name="tday" class="small" size="2" value="<?=$today?>">
				<input type="text" name="tyear" class="small" size="4" value="<?=$thisyear?>">
			</td>
		</tr>
	</table>
	<br><bR>
	<table width="580" border="0" cellpadding="0" cellspacing="10" align="center" bordercolor="#E0E0E0">
	<tr>
		<td>
			<input type=checkbox name=campaign_display checked>
		</td>
		<td> 
			If there is no campaign activity in selected time period, do not display these campaigns.
		</td>
	</tr>
	<tr>
		<td>
			<input type=checkbox name=subcampaign_display checked>
		</td>
		<td> 
			If there is no subcampaign activity in selected time period, do not display these subcampaigns
		</td>
	</tr>
	</table>

	<p><u>Step 2: Select Columns</u></p>
	<p>Select the columns you would like to display for the statistics report. You can also choose how the data is separated by entering the field separator. </p>
	<form action="export.php" method="post">
	<table border="0" cellspacing="0" cellpadding="5" align="center" bgcolor="white"  bordercolor="white">
	<tr>
		<td valign="top">Field Separator (use ## for tab)</td>
		<td valign="top">
			<?
			if (!$separator)
				$separator = ","; //default value
			?>
			<input type="text" size="6" name="separator" value="<?=$separator?>"> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Use quotes ("") round fields?</td>
		<td valign="top">
			<input type="checkbox" name="yesquotes" value="checked" <?=$yesquotes?>> 		
		</td>

	</tr>
	<tr>
		<td valign="top">Raw Clicks</td>
		<td valign="top">
			<input type="checkbox" name="column_rawclicks" value="checked" <?=$column_rawclicks?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Clicks</td>
		<td valign="top">
			<input type="checkbox" name="column_clicks" value="checked" <?=$column_clicks?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Actions</td>
		<td valign="top">
			<input type="checkbox" name="column_actions" value="checked" <?=$column_actions?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Sales</td>
		<td valign="top">
			<input type="checkbox" name="column_sales" value="checked" <?=$column_sales?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Cost Per Click (CPC)</td>
		<td valign="top">
			<input type="checkbox" name="column_cpc" value="checked" <?=$column_cpc?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Cost Per Action (CPA)</td>
		<td valign="top">
			<input type="checkbox" name="column_cpa" value="checked" <?=$column_cpa?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Cost Per Sale (CPS)</td>
		<td valign="top">
			<input type="checkbox" name="column_cps" value="checked" <?=$column_cps?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Clicks to Actions % (CTA)</td>
		<td valign="top">
			<input type="checkbox" name="column_cta" value="checked" <?=$column_cta?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Clicks to Sales % (CTS)</td>
		<td valign="top">
			<input type="checkbox" name="column_cts" value="checked" <?=$column_cts?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Cost</td>
		<td valign="top">
			<input type="checkbox" name="column_cost" value="checked" <?=$column_cost?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Revenue</td>
		<td valign="top">
			<input type="checkbox" name="column_revenue" value="checked" <?=$column_rev?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Profit</td>
		<td valign="top">
			<input type="checkbox" name="column_profit" value="checked" <?=$column_profit?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">R.O.I.</td>
		<td valign="top">
			<input type="checkbox" name="column_roi" value="checked" <?=$column_roi?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Purpose</td>
		<td valign="top">
			<input type="checkbox" name="column_purpose" value="checked" <?=$column_purpose?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Group</td>
		<td valign="top">
			<input type="checkbox" name="column_group" value="checked" <?=$column_group?>> 		
		</td>
	</tr>
	<tr>
		<td valign="top">Description</td>
		<td valign="top">
			<input type="checkbox" name="column_description" value="checked" <?=$column_description?>> 		
		</td>
	</tr>
	</table>

	<br><br>
	<center>
	<input type=submit name=preview value="Preview Report">
	&nbsp;&nbsp;
	<input type=submit name=export value="Export Data">
	<input type=hidden name=runcode value=yes>
	</center>
	</form>
	<?
}
else
{
	if ($preview)
	{
		?>
		<p>Here is the actual data that you are exporting. If you want this data to be exported, click export. If not, click <a href="javascript: history.go(-1)">here</a> to go back and create a new report.</p>

		<form action=export.php method=post>
		<center>
		<input type="hidden" name="group" value=<?=$group?>>
		<input type="hidden" name="purpose" value="<?=$purpose?>">
		<input type="hidden" name="status" value=<?=$status?>>
		<input type="hidden" name="timeperiod" value=<?=$timeperiod?>>
		<input type="hidden" name="submit_bottom" value=<?=$submit_bottom?>>
		<input type="hidden" name="fyear" value=<?=$fyear?>>
		<input type="hidden" name="fday" value=<?=$fday?>>
		<input type="hidden" name="fmonth" value=<?=$fmonth?>>
		<input type="hidden" name="tyear" value=<?=$tyear?>>
		<input type="hidden" name="tmonth" value=<?=$tmonth?>>
		<input type="hidden" name="tday" value=<?=$tday?>>
		<input type="hidden" name="campaign_display" value=<?=$campaign_display?>>
		<input type="hidden" name="subcampaign_display" value=<?=$subcampaign_display?>>
		<input type="hidden" name="column_rawclicks" value=<?=$column_rawclicks?>>
		<input type="hidden" name="column_clicks" value=<?=$column_clicks?>>
		<input type="hidden" name="column_actions" value=<?=$column_actions?>>
		<input type="hidden" name="column_sales" value=<?=$column_sales?>>
		<input type="hidden" name="column_cta" value=<?=$column_clicks?>>
		<input type="hidden" name="column_cts" value=<?=$column_cta?>>
		<input type="hidden" name="column_cpc" value=<?=$column_cpc?>>
		<input type="hidden" name="column_cpa" value=<?=$column_cpa?>>
		<input type="hidden" name="column_cps" value=<?=$column_cps?>>
		<input type="hidden" name="column_cost" value=<?=$column_cost?>>
		<input type="hidden" name="column_rev" value=<?=$column_rev?>>
		<input type="hidden" name="column_profit" value=<?=$column_profit?>>
		<input type="hidden" name="column_roi" value=<?=$column_roi?>>
		<input type="hidden" name="column_group" value=<?=$column_group?>>
		<input type="hidden" name="column_purpose" value=<?=$column_purpose?>>
		<input type="hidden" name="column_description" value=<?=$column_description?>>
		<input type="hidden" name="yesquotes" value=<?=$yesquotes?>>
		<input type="hidden" name="separator" value=<?=$separator?>>
		<input type=submit name=export value="Export Data">
		<input type=hidden name=runcode value=yes>
		</form>	
		</center>
		<br><br>
		<?
	}
	if ($export)
	{
		?>
		<p>Here is your report. To save it to your computer, right click and choose save as.</p>
		<br>
		<center><?="<a href=http://$domain/$udirectory/export.csv>export.csv</a>"?></center>
		<br><br>
		<?		
	}

	#####################################
	//STATS CODE, PREPATE DATA
	#####################################




	//STEP 1: FILTER BY PURPOSE, GROUP
	// all dynamic campaigns have purpose == all, group=dynamic
	if ($purpose == "all purposes" && $group == "all")
		$campaigns = mysql_query("select * from adtrackz_campaigns");
	elseif ($purpose == "all purposes" && $group != "all")
	{
		if ($group == "default")
			$group = 0;
		$campaigns = mysql_query("select * from adtrackz_campaigns where groupID = '$group'");
	}
	elseif($purpose != "all purposes" && $group == "all")
		$campaigns = mysql_query("select * from adtrackz_campaigns where purpose = '$purpose'");
	else
	{
		$campaigns = mysql_query("select * from adtrackz_campaigns where  groupID = '$group' && purpose = '$purpose'");
	}

	//STEP 2: FILTER BY STATUS
	// all dynamic campaigns are constantly running, so "all"
	$now = date("Y-m-d H:m:s");
	if ($status == "active")
	{
		while($campaign1 = mysql_fetch_row($campaigns))
		{
			//if now is in between startdate and enddate
			if (earlier_date($now,$campaign1[5]) == $campaign1[5] && earlier_date($now,$campaign1[6]) == $now)
				$campaignIDs1[$campaign1[0]]=$campaign1[2];
		}
	}
	elseif ($status == "ended")
	{
		while($campaign1 = mysql_fetch_row($campaigns))
		{
			// enddate is before now (campaign has ended)
			if (earlier_date($now,$campaign1[6]) == $campaign1[6])
				$campaignIDs1[$campaign1[0]]=$campaign1[2];
		}
	}
	elseif ($status == "pending")
	{
		while($campaign1 = mysql_fetch_row($campaigns))
		{
			//now is before startdate (campaign hasn't started yet)
			if (earlier_date($now,$campaign1[5]) == $now)
				$campaignIDs1[$campaign1[0]]=$campaign1[2];
		}
	}
	elseif ($status == "all")
	{
		while($campaign1 = mysql_fetch_row($campaigns))
			$campaignIDs1[$campaign1[0]]=$campaign1[2];
	}


	//STEP 3 - take out any split test campaigns
	if ($campaignIDs1)
	{
		foreach ($campaignIDs1 as $campaignID => $adcode)
		{
			//if campaign is not in list of split test campaigns, add it, otherwise, don't
			$st = mysql_fetch_row(mysql_query("select st from adtrackz_campaigns_st where campaignID='$campaignID'"));
			if (!$st[0])
				$campaignIDs[$campaignID] = $adcode;	
		}
	}

	//sort array
	if ($campaignIDs)
		asort($campaignIDs);

	//now we have our list of campaigns to display in the stats report
	if ($campaignIDs)
	{

		if ($submit_bottom)
		{
			$from_timestamp = mktime (0,0,0,$fmonth,$fday,$fyear); 
			$to_timestamp = mktime (23,59,59,$tmonth,$tday,$tyear); 
		}
		else
		{
			//CONVERT TIME PERIOD INTO TIME STAMP
			if ($timeperiod == "all")
			{
				$from_timestamp = mktime (0,0,0,1,1,2004); 
				$to_timestamp = mktime (0,0,0,12,31,2014);  
			}
			elseif ($timeperiod == "today")
			{
				$from_timestamp = mktime (0,0,0,date("m"),date("d"),date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m"),date("d"),date("Y")); 
			}
			elseif ($timeperiod == "yesterday")
			{
				$from_timestamp = mktime (0,0,0,date("m"),date("d")-1,date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m"),date("d")-1,date("Y")); 
			}
			elseif ($timeperiod == "thisweek")
			{
			//0 (for Sunday) through 6 (for Saturday)
				$day_of_week = date("w");
				$from_timestamp = mktime (0,0,0,date("m"),date("d")-$day_of_week,date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m"),date("d")+(6-$day_of_week),date("Y")); 
			}
			elseif ($timeperiod == "lastweek")
			{
				$day_of_week = date("w");
				$from_timestamp = mktime (0,0,0,date("m"),date("d")-(7+$day_of_week),date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m"),date("d")-($day_of_week+1),date("Y")); 
			}
			elseif ($timeperiod == "thismonth")
			{
				$days_in_month = date("t");
				$from_timestamp = mktime (0,0,0,date("m"),01,date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m"),$days_in_month,date("Y")); 
			}
			elseif ($timeperiod == "lastmonth")
			{
				$days_in_month = date("t");
				$from_timestamp = mktime (0,0,0,date("m")-1,01,date("Y")); 
				$to_timestamp = mktime (23,59,59,date("m")-1,$days_in_month,date("Y"));
			}
			elseif ($timeperiod == "thisyear")
			{
				$from_timestamp = mktime (0,0,0,01,01,date("Y")); 
				$to_timestamp = mktime (23,59,59,12,31,date("Y"));
			}
			elseif ($timeperiod == "lastyear")
			{
				$from_timestamp = mktime (0,0,0,01,01,date("Y")-1); 
				$to_timestamp = mktime (23,59,59,12,31,date("Y")-1);
			}
			else
				alert("invalid time period");	
		}


		if ($from_timestamp > $to_timestamp)
		{
			alert("The from time period you have chosen should be earlier than the to time period.");
			echo "<br>";
		}


		//fetch preferences data
		//$pref = mysql_fetch_assoc(mysql_query("select * from adtrackz_preferences"));
		$pref['rawclicks'] = $column_rawclicks;
		$pref['clicks'] = $column_clicks;
		$pref['actions'] = $column_actions;
		$pref['sales'] = $column_sales;
		$pref['cta'] = $column_cta;
		$pref['cts'] = $column_cts;
		$pref['cpc'] = $column_cpc;
		$pref['cpa'] = $column_cpa;
		$pref['cps'] = $column_cps;
		$pref['cost'] = $column_cost;
		$pref['revenue'] = $column_revenue;
		$pref['profit'] = $column_profit;
		$pref['roi'] = $column_roi;
		$pref['column_purpose'] = $column_purpose;
		$pref['column_group'] = $column_group;
		$pref['description'] = $column_description;
		$pref['campaign_display'] = $campaign_display;
		$pref['subcampaign_display'] = $subcampaign_display;

		if ($preview)
		{
			//THE MAIN STATS TABLE
			echo "<!--- THE MAIN STATS TABLE -->";
			echo "<table border=1 cellspacing=0 cellpadding=5 align=center>";
			echo "<tr bgcolor=#FA7F14 >";
			echo "<td class=tbhead2>Campaigns</td>";
			if ($pref['rawclicks'])
				echo "<td class=tbhead2>Raw Clicks</td>";
			if ($pref['clicks'])
				echo "<td class=tbhead2>Clicks</td>";
			if ($pref['actions'])
				echo "<td class=tbhead2>Actions</td>";
			if ($pref['sales'])
				echo "<td class=tbhead2>Sales</td>";
			if ($pref['cta'])
				echo "<td class=tbhead2>CTA</td>";
			if ($pref['cts'])
				echo "<td class=tbhead2>CTS</td>";
			if ($pref['cpc'])
				echo "<td class=tbhead2>Avg CPC</td>";
			if ($pref['cpa'])
				echo "<td class=tbhead2>CPA</td>";
			if ($pref['cps'])
				echo "<td class=tbhead2>CPS</td>";
			if ($pref['cost'])
				echo "<td class=tbhead2>Cost</td>";
			if ($pref['revenue'])
				echo "<td class=tbhead2>Revenue</td>";
			if ($pref['profit'])
				echo "<td class=tbhead2>Profit</td>";
			if ($pref['roi'])
				echo "<td class=tbhead2>R.O.I.</td>";
			if ($pref['column_purpose'])
				echo "<td class=tbhead2>Purpose</td>";
			if ($pref['column_group'])
				echo "<td class=tbhead2>Group</td>";
			if ($pref['description'])
				echo "<td class=tbhead2>Description</td>";
			echo "</tr>";
		}
		elseif ($export)
		{
			//file open, print this
			//create string for this row
			$b=0;
			if ($pref['rawclicks'])
			{
				$thisrow[$b] = "Raw Clicks";
				$b += 1;
			}
			if ($pref['clicks'])
			{
				$thisrow[$b] = "Clicks";
				$b += 1;
			}
			if ($pref['actions'])
			{
				$thisrow[$b] = "Actions";
				$b += 1;
			}			
			if ($pref['sales'])
			{
				$thisrow[$b] = "Sales";
				$b += 1;
			}
			if ($pref['cta'])
			{
				$thisrow[$b] = "CTA";
				$b += 1;
			}
			if ($pref['cts'])
			{
				$thisrow[$b] = "CTS";
				$b += 1;
			}
			if ($pref['cpc'])
			{
				$thisrow[$b] = "Avg CPC";
				$b += 1;
			}
			if ($pref['cpa'])
			{
				$thisrow[$b] = "CPA";
				$b += 1;
			}
			if ($pref['cps'])
			{
				$thisrow[$b] = "CPS";
				$b += 1;
			}
			if ($pref['cost'])
						{
				$thisrow[$b] = "Cost";
				$b += 1;
			}
			if ($pref['revenue'])
			{
				$thisrow[$b] = "Revenue";
				$b += 1;
			}
			if ($pref['profit'])
			{
				$thisrow[$b] = "Profits";
				$b += 1;
			}
			if ($pref['roi'])
			{
				$thisrow[$b] = "R.O.I.";
				$b += 1;
			}
			if ($pref['column_purpose'])
			{
				$thisrow[$b] = "Purpose";
				$b += 1;
			}
			if ($pref['column_group'])
			{
				$thisrow[$b] = "Group";
				$b += 1;
			}
			if ($pref['description'])
			{
				$thisrow[$b] = "Description";
				$b += 1;
			}

			//massage data
			$header = "Campaign,";
			for ($i=0;$i<$b;$i++)
			{
				if ($yesquotes)
					$quotes = '"';

				if ($separator == "##")
					$separator = "\t"; //tab

				if ($i == $b-1) //last line, no need for separator
					$header .= $quotes.$thisrow[$i].$quotes;
				else
					$header .= $quotes.$thisrow[$i].$quotes.$separator;
			}
			
			$filedata .= $header."\n";
			unset ($thisrow,$header);
		}

	

		//MAIN STATS FOREACH LOOP - loop through each campaign
		 $c = 0; //to keep track of alternating rows for bg color
		foreach ($campaignIDs as $campaignID => $adcode1)
		{	
			//fetch campaign data for later use
			$campaign = mysql_fetch_assoc(mysql_query("select * from adtrackz_campaigns where ID='$campaignID'"));

			//affiliate tracking is the same as purpose=all for stats table
			if ($campaign['purpose'] == "affiliate")
				$campaign['purpose'] = "all";

			//get data for this campaign for this time period
			$rawclicks = get_campaign_data("rawclicks",$campaignID);
			$clicks = get_campaign_data("clicks",$campaignID);
			$actions = get_campaign_data("actions",$campaignID);
			$sales = get_campaign_data("sales",$campaignID);

			//get data for subcampaigns - using 2 dimensional array to store 
			$subcampaigns = mysql_query("select * from adtrackz_subcampaigns where campaignID='$campaignID' order by adcode asc");
			$subdata_flag = false; //if no subcampaigns, then make sure this is set to false
			while ($sub = mysql_fetch_assoc($subcampaigns))
			{
				$sub_adcode = $sub['adcode'];
				$subID = $sub['ID'];
				$subdata[$sub_adcode]['rawclicks'] = get_subcampaign_data("rawclicks",$campaignID, $subID);
				$subdata[$sub_adcode]['clicks'] = get_subcampaign_data("clicks",$campaignID, $subID);
				$subdata[$sub_adcode]['actions'] = get_subcampaign_data("actions",$campaignID, $subID);
				$subdata[$sub_adcode]['sales'] = get_subcampaign_data("sales",$campaignID, $subID);

				$sub_rawclicks = $subdata[$sub_adcode]['rawclicks'];
				$sub_clicks = $subdata[$sub_adcode]['clicks'];
				$sub_actions = $subdata[$sub_adcode]['actions'];
				$sub_sales = $subdata[$sub_adcode]['sales'];
				
				if ($sub_rawclicks || $sub_clicks || $sub_actions || $sub_sales)
					$subdata_flag = true;		
			}
			
			//if no activity in this campaign and no activity in it's subcampaigns for this time period, 
			//then don't display this campaign
			//get prefences
			// && pref = don't display 
			if (!$rawclicks && !$clicks && !$actions && !$sales && $subdata_flag === false && $pref['campaign_display'])
				continue;

			//CALCULATE COST
			if ($campaign['ppc'])
			{
				//true cost
				$cpc_data = mysql_fetch_row(mysql_query("select sum(cpc) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag = 1"));
				//cost is sum of all clicks in this period, 
				//remember that in go.php if click doesn't have cpc set, then default cpc from campaign is used
				//therefore, cpc should always have a value
				$cost = $cpc_data[0];
			}
			elseif ($campaign['recurdays'] && $campaign['repeat']) 
			{
				//cost = from start date to now 
				$now = time();
				$startdate = strtotime($campaign['startdate']);

				//cycles so far, expressed in days
				$cycles = (($now - $startdate) / 86400) / $campaign['recurdays']; 
				if ($cycles > $campaign['repeat']) //user defines how many cycles
					$cycles = $campaign['repeat'];
				$cost = $cycles * $campaign['cost']; //abs cost is # of cycles * specified campaign cost				
			}
			else //normal cost
				$cost = $campaign['cost'];

			//CALCULATE VALUES - get rid of zeros
			$cta = (!$clicks ? 0 : $actions / $clicks * 100);	
			$cts = (!$clicks ? 0 : $sales / $clicks * 100);
			$cpc = (!$clicks ? 0 : $cost / $clicks);
			$cpa = (!$actions ? 0 : $cost / $actions);
			$cps = (!$sales ? 0 : $cost / $sales);
			$revdata = mysql_fetch_row(mysql_query("select sum(revenue) from adtrackz_sales where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
			$rev = $revdata[0];
			$profit = $rev - $cost;
			//$roi = $revenue / $cost * 100	??
			$roi = (!$cost ? 0 : ($profit / $cost) * 100);

			//ADD TOTALS (before formatting values)
			$total_rawclicks += $rawclicks;
			$total_clicks += $clicks;
			$total_actions += $actions;
			$total_sales += $sales;
			$total_cta += $cta;
			$total_cts += $cts;
			$total_cpc += $cpc;
			$total_cpa += $cpa;
			$total_cps += $cps;
			$total_cost += $cost;
			$total_rev += $rev;
			$total_profit += $profit;
			$total_roi += $roi;
			//rows
			if ($cta)
				$total_rows['cta'] += 1; 
			if ($cts)
				$total_rows['cts'] += 1; 
			if ($cpc)
				$total_rows['cpc'] += 1; 
			if ($cpa)
				$total_rows['cpa'] += 1; 
			if ($cps)
				$total_rows['cps'] += 1; 
			if ($roi)
				$total_rows['roi'] += 1; 

			//FORMAT VALUES
			if ($preview) //don't format if they choose export ot the commas will screw up the csv file
			{
				$rawclicks = number_format($rawclicks, 0);
				$clicks = number_format($clicks, 0);
				$actions = number_format($actions, 0);
				$sales = number_format($sales, 0);
				$cta = (!$cta ? 0 : number_format($cta, 2));
				$cts = (!$cts ? 0 : number_format($cts, 2));
				$cpc = (!$cpc ? 0 : number_format($cpc, 2));
				$cpa = (!$cpa ? 0 : number_format($cpa, 2));
				$cps = (!$cps ? 0 : number_format($cps, 2));
				$rev = (!$rev ? 0 : number_format($rev, 2));
				$cost = (!$cost ? 0 : number_format($cost, 2));
				$profit = (!$profit ? 0 : number_format($profit, 2));		
				$roi = (!$roi ? 0 : number_format($roi, 2));
			}

			//SET STATUSPIC
			$now = date("Y-m-d H:i:s"); 
			if ((earlier_date ($campaign['startdate'], $now) == $campaign['startdate']) && (earlier_date ($campaign['enddate'], $now) == $now))
				$statuspic = "inprogress3.gif";
			elseif ((earlier_date ($campaign['startdate'], $now) == $campaign['startdate']) && (earlier_date ($campaign['enddate'], $now) == $campaign['enddate']))
				$statuspic = "ended3.gif";
			elseif (earlier_date ($campaign['startdate'], $now) == $now)
				$statuspic = "scheduled3.gif";

			if ($preview)
			{
				//alternate bg colors between campaigns
				$c++;
				//need better colors
				if (!($c % 2))
					$tr = "<tr bgcolor=#F0F0F0>";
				else
					$tr = "<tr bgcolor=d8d8d8>";

				//massage adcode to break at 30 char
				$wcampaign_adcode = wordwrap($campaign['adcode'],30,"<br>",1);

				echo $tr;
				echo '<td align="left"><table><tr><td valign=top><img src="'.$statuspic.'"></td><td><a href="dstats-summary.php?cID='.$campaign['ID'].'">'.$wcampaign_adcode.'</a></td></tr></table></td>';				
				if ($pref['rawclicks'])
					echo "<td class=tb1>$rawclicks</td>";
				if ($pref['clicks'])
					echo "<td class=tb1>$clicks</td>";
				if ($pref['actions'])
					echo "<td class=tb1>$actions</td>";
				if ($pref['sales'])
					echo "<td class=tb1>$sales</td>";
				if ($pref['cta'])
					echo "<td class=tb1>$cta%</td>";
				if ($pref['cts'])
					echo "<td class=tb1>$cts%</td>";
				if ($pref['cpc'])
					echo "<td class=tb1>\$$cpc</td>";
				if ($pref['cpa'])
					echo "<td class=tb1>\$$cpa</td>";
				if ($pref['cps'])
					echo "<td class=tb1>\$$cps</td>";
				if ($pref['cost'])
					echo "<td class=tb1>\$$cost</td>";
				if ($pref['revenue'])
					echo "<td class=tb1>\$$rev</td>";
				if ($pref['profit'])
				{
					if ($profit < 0)
						echo "<td class=tb1><font color=#F51800>\$$profit</font></td>";
					else
						echo "<td class=tb1><font color=#FFFFFF>\$$profit</font></td>";
				}
				if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
				{
					if ($roi < 0 ) 
						echo "<td class=tb1><font color=#F51800>$roi%</font></td>";
					else
						echo "<td class=tb1><font color=#FFFFFF>$roi%</font></td>";
				}
				if ($pref['column_purpose'])
					echo "<td class=tb1>&nbsp;".$campaign['purpose']."</td>";
				if ($pref['column_group'])
				{			
					if (!$campaign['groupID'])
						echo "<td class=tb1>&nbsp;default</td>";
					else
					{
						$cgroup = mysql_fetch_row(mysql_query("select groupname from adtrackz_groups where ID='".$campaign['groupID']."'"));	
						echo "<td class=tb1>&nbsp;$cgroup[0]</td>";
					}
				}
				if ($pref['description'])
					echo "<td class=tb1>&nbsp;".$campaign['description']."</td>";				
				echo "</tr>";
			}
			elseif ($export)
			{

			//file open, print this
				//create string for this row
				$b=0;
				if ($pref['rawclicks'])
				{
					$thisrow[$b] = $rawclicks;
					$b += 1;
				}
				if ($pref['clicks'])
				{
					$thisrow[$b] = $clicks;
					$b += 1;
				}
				if ($pref['actions'])
				{
					$thisrow[$b] = $actions;
					$b += 1;
				}			
				if ($pref['sales'])
				{
					$thisrow[$b] = $sales;
					$b += 1;
				}
				if ($pref['cta'])
				{
					$thisrow[$b] = $cta;
					$b += 1;
				}
				if ($pref['cts'])
				{
					$thisrow[$b] = $cts;
					$b += 1;
				}
				if ($pref['cpc'])
				{
					$thisrow[$b] = $cpc;
					$b += 1;
				}
				if ($pref['cpa'])
				{
					$thisrow[$b] = $cpa;
					$b += 1;
				}
				if ($pref['cps'])
				{
					$thisrow[$b] = $cps;
					$b += 1;
				}
				if ($pref['cost'])
							{
					$thisrow[$b] = $cost;
					$b += 1;
				}
				if ($pref['revenue'])
				{
					$thisrow[$b] = $revenue;
					$b += 1;
				}
				if ($pref['profit'])
				{
					$thisrow[$b] = $profits;
					$b += 1;
				}
				if ($pref['roi'])
				{
					$thisrow[$b] = $roi;
					$b += 1;
				}
				if ($pref['column_purpose'])
				{
					$thisrow[$b] = $campaign['purpose'];
					$b += 1;
				}
				if ($pref['column_group'])
				{
					$thisrow[$b] = $campaign['group'];
					$b += 1;
				}
				if ($pref['description'])
				{
					$thisrow[$b] = $campaign['description'];
					$b += 1;
				}

				

				//massage data
				$header = $campaign['adcode'].",";
				for ($i=0;$i<$b;$i++)
				{
					if ($yesquotes)
						$quotes = '"';

					if ($separator == "##")
						$separator = "\t"; //tab

					if ($i == $b-1) //last line, no need for separator
						$header .= $quotes.$thisrow[$i].$quotes;
					else
						$header .= $quotes.$thisrow[$i].$quotes.$separator;

					
				}
				
				$filedata .= $header."\n";
				unset ($thisrow,$header);
			}



			//LIST OF SUBCAMPAIGNS FOR THIS CAMPAIGN
			$subcampaigns = mysql_query("select * from adtrackz_subcampaigns where campaignID='$campaignID' order by adcode asc");
			while ($sub = mysql_fetch_assoc($subcampaigns))
			{
				$sub_adcode = $sub['adcode'];
				//get subcampaign data
				$sub_rawclicks = $subdata[$sub_adcode]['rawclicks'];
				$sub_clicks = $subdata[$sub_adcode]['clicks'];
				$sub_actions = $subdata[$sub_adcode]['actions'];
				$sub_sales = $subdata[$sub_adcode]['sales'];
				//if no data to display, skip it
				//get prefences
				// && pref = don't display 
				if (!$sub_rawclicks && !$sub_clicks && !$sub_actions && !$sub_sales && $pref['subcampaign_display'])
					continue;

				//CALCULATE COST
				if ($sub['ppc'])
				{
					$sub_cpc_data = mysql_fetch_row(mysql_query("select sum(cpc) from adtrackz_clicks where campaignID='$campaignID' && subID = ".$sub['ID']." && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag = 1"));
					//cost is sum of all clicks in this period, 
					//remember that in go.php if click doesn't have cpc set, then default cpc from campaign is used
					//therefore, cpc should always have a value
					$sub_cost = $sub_cpc_data[0];
				}
				else //normal cost
				{
					$sub_cost = $sub['cost'];
				}

				//CALCULATE OTHER VALUES - get rid of zeros
				$sub_cta = (!$sub_clicks ? 0 : $sub_actions / $sub_clicks * 100);	
				$sub_cts = (!$sub_clicks ? 0 : $sub_sales / $sub_clicks * 100);
				$sub_cpc = (!$sub_clicks ? 0 : $sub_cost / $sub_clicks);		
				$sub_cpa = (!$sub_actions ? 0 : $sub_cost / $sub_actions);
				$sub_cps = (!$sub_sales ? 0 : $sub_cost / $sub_sales);
				$sub_revdata = mysql_fetch_row(mysql_query("select sum(revenue) from adtrackz_sales where campaignID='$campaignID' && subID = ".$sub['ID']." && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
				$sub_rev = $sub_revdata[0];
				$sub_profit = $sub_rev - $sub_cost;
				//$roi = $revenue / $cost * 100	??
				$sub_roi = (!$sub_cost ? 0 : $sub_profit / $sub_cost * 100);

				//ADD TOTALS - (before formatting values for display)
				$total_rawclicks += $sub_rawclicks;
				$total_clicks += $sub_clicks;
				$total_actions += $sub_actions;
				$total_sales += $sub_sales;
				$total_cta += $sub_cta;
				$total_cts += $sub_cts;
				$total_cpc += $sub_cpc;
				$total_cpa += $sub_cpa;
				$total_cps += $sub_cps;
				$total_cost += $sub_cost;
				$total_rev += $sub_rev;
				$total_profit += $sub_profit;
				$total_roi += $sub_roi;
				//rows
				if ($sub_cta)
					$total_rows['cta'] += 1; 
				if ($sub_cts)
					$total_rows['cts'] += 1; 
				if ($sub_cpc)
					$total_rows['cpc'] += 1; 
				if ($sub_cpa)
					$total_rows['cpa'] += 1; 
				if ($sub_cps)
					$total_rows['cps'] += 1; 
				if ($sub_roi)
					$total_rows['roi'] += 1; 

				//FORMAT VALUES
				if ($preview)
				{
					$sub_rawclicks = number_format($sub_rawclicks, 0);
					$sub_clicks = number_format($sub_clicks, 0);
					$sub_actions = number_format($sub_actions, 0);
					$sub_sales = number_format($sub_sales, 0);
					$sub_cta = (!$sub_cta ? 0 : number_format($sub_cta, 2));
					$sub_cts = (!$sub_cts ? 0 : number_format($sub_cts, 2));
					$sub_cpc = (!$sub_cpc ? 0 : number_format($sub_cpc, 2));
					$sub_cpa = (!$sub_cpa ? 0 : number_format($sub_cpa, 2));
					$sub_cps = (!$sub_cps ? 0 : number_format($sub_cps, 2));
					$sub_rev = (!$sub_rev ? 0 : number_format($sub_rev, 2));
					$sub_cost = (!$sub_cost ? 0 : number_format($sub_cost, 2));
					$sub_profit = (!$sub_profit ? 0 : number_format($sub_profit, 2));		
					$sub_roi = (!$sub_roi ? 0 : number_format($sub_roi, 2));
					//DISPLAY SUBCAMPAIGN ROW(do we need to * the actions if actions is not purpose of campaign?)
					//dstats-summary.php?cID='.$campaign[0].'&stats_select='.$s.'  <- um... this was 3.13 call to detailed stats sub
				}

				if ($preview)
				{
					if (!($c % 2))
						$tr = "<tr bgcolor=#F0F0F0>";
					else
						$tr = "<tr bgcolor=d8d8d8>";
					echo $tr;

					//massage adcode, max 30 chars on one line						
					$separator = "<br><span style=margin:25pt;></span>";
					$wsub_adcode = wordwrap($sub['adcode'],30,$separator,1);
					
					echo '<td><span style=margin:25pt;><a href="dstats-summary.php?cID='.$campaign['ID'].'&sID='.$sub['ID'].'">'.$wsub_adcode.'</a></span></td>';					
					if ($pref['rawclicks'])
						echo "<td class=tb1>$sub_rawclicks</td>";
					if ($pref['clicks'])
						echo "<td class=tb1>$sub_clicks</td>";
					if ($pref['actions'])
						echo "<td class=tb1>$sub_actions</td>";
					if ($pref['sales'])
						echo "<td class=tb1>$sub_sales</td>";
					if ($pref['cta'])
						echo "<td class=tb1>$sub_cta%</td>";
					if ($pref['cts'])
						echo "<td class=tb1>$sub_cts%</td>";
					if ($pref['cpc'])
						echo "<td class=tb1>\$$sub_cpc</td>";
					if ($pref['cpa'])
						echo "<td class=tb1>\$$sub_cpa</td>";
					if ($pref['cps'])
						echo "<td class=tb1>\$$sub_cps</td>";
					if ($pref['cost'])
						echo "<td class=tb1>\$$sub_cost</td>";
					if ($pref['revenue'])
						echo "<td class=tb1>\$$sub_rev</td>";
					if ($pref['profit'])
					{
						if ($sub_profit < 0)
							echo "<td class=tb1><font color=#F51800>\$$sub_profit</font></td>";
						else
							echo "<td class=tb1><font color=#0F87BE>\$$sub_profit</font></td>";
					}
					if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
					{
						if ($sub_roi < 0 ) 
							echo "<td class=tb1><font color=#F51800>$sub_roi%</font></td>";
						else
							echo "<td class=tb1><font color=#FFFFFF>$sub_roi%</font></td>";
					}
					if ($pref['column_purpose'])
						echo "<td class=tb1>&nbsp;".$campaign['purpose']."</td>";
					if ($pref['column_group'])
					{			
						if (!$campaign['groupID'])
							echo "<td class=tb1>&nbsp;default</td>";
						else
						{
							$cgroup = mysql_fetch_row(mysql_query("select groupname from adtrackz_groups where ID='".$campaign['groupID']."'"));	
							echo "<td class=tb1>&nbsp;$cgroup[0]</td>";
						}
					}
					if ($pref['description'])
					{
						if ($sub['description'])
							echo "<td class=tb1>".$sub['description']."</td>";	
						else
							echo "<td class=tb1>&nbsp;</td>";	
					}
					echo "</tr>";
				}
				elseif ($export)
				{
					//file open, print this
					//create string for this row
					$b=0;
					if ($pref['rawclicks'])
					{
						$thisrow[$b] = $sub_rawclicks;
						$b += 1;
					}
					if ($pref['clicks'])
					{
						$thisrow[$b] = $sub_clicks;
						$b += 1;
					}
					if ($pref['actions'])
					{
						$thisrow[$b] = $sub_actions;
						$b += 1;
					}			
					if ($pref['sales'])
					{
						$thisrow[$b] = $sub_sales;
						$b += 1;
					}
					if ($pref['cta'])
					{
						$thisrow[$b] = $sub_cta;
						$b += 1;
					}
					if ($pref['cts'])
					{
						$thisrow[$b] = $sub_cts;
						$b += 1;
					}
					if ($pref['cpc'])
					{
						$thisrow[$b] = $sub_cpc;
						$b += 1;
					}
					if ($pref['cpa'])
					{
						$thisrow[$b] = $sub_cpa;
						$b += 1;
					}
					if ($pref['cps'])
					{
						$thisrow[$b] = $sub_cps;
						$b += 1;
					}
					if ($pref['cost'])
								{
						$thisrow[$b] = $sub_cost;
						$b += 1;
					}
					if ($pref['revenue'])
					{
						$thisrow[$b] = $sub_revenue;
						$b += 1;
					}
					if ($pref['profit'])
					{
						$thisrow[$b] = $sub_profits;
						$b += 1;
					}
					if ($pref['roi'])
					{
						$thisrow[$b] = $sub_roi;
						$b += 1;
					}
					if ($pref['column_purpose'])
					{
						$thisrow[$b] = $campaign['purpose'];
						$b += 1;
					}
					if ($pref['column_group'])
					{
						$thisrow[$b] = $campaign['group'];
						$b += 1;
					}
					if ($pref['description'])
					{
						$thisrow[$b] = $sub['description'];
						$b += 1;
					}


					//massage data
					$header = $sub['adcode'].",";
					for ($i=0;$i<$b;$i++)
					{
						if ($yesquotes)
							$quotes = '"';

						if ($separator == "##")
							$separator = "\t"; //tab

						if ($i == $b-1) //last line, no need for separator
							$header .= $quotes.$thisrow[$i].$quotes;
						else
							$header .= $quotes.$thisrow[$i].$quotes.$separator;

						
					}
					
					$filedata .= $header."\n";
					unset ($thisrow,$header);
				}

				unset ($sub_rawclicks, $sub_clicks, $sub_actions, $sub_sales, $sub_cta, $sub_cts, $sub_cpc, $sub_cpa, $sub_cps, $sub_cost, $sub_rev, $sub_profit, $sub_roi);
			}
			unset ($subdata_flag, $rawclicks, $clicks, $actions, $sales, $cta, $cts, $cpc, $cpa, $cps, $cost, $rev, $profit, $roi);
		} // end campaigns loop

		//CALCULATE TOTALS (get averages)
		//fix: may 5th
		//instead of taking average of rows, calculate in terms of other totals
		$total_cta = (!$total_clicks ? 0 : $total_actions / $total_clicks * 100);	
		$total_cts = (!$total_clicks ? 0 : $total_sales / $total_clicks * 100);
		$total_cpc = (!$total_clicks ? 0 : $total_cost / $total_clicks);
		$total_cpa = (!$total_actions ? 0 : $total_cost / $total_actions);
		$total_cps = (!$total_sales ? 0 : $total_cost / $total_sales);
		$total_roi = (!$total_cost ? 0 : ($total_profit / $total_cost) * 100);

		//fix: may 5th
		//instead of taking average of rows, calculate in terms
		//of total profit and total cost	
		$total_roi = (!$total_cost ? 0 : ($total_profit / $total_cost) * 100);

		//FORMAT TOTALS
		if ($preview)
		{
			$total_rawclicks = number_format($total_rawclicks, 0);
			$total_clicks = number_format($total_clicks, 0);
			$total_actions = number_format($total_actions, 0);
			$total_sales = number_format($total_sales, 0);
			$total_cta = (!$total_cta ? 0 : number_format($total_cta, 2));
			$total_cts = (!$total_cts ? 0 : number_format($total_cts, 2));
			$total_cpc = (!$total_cpc ? 0 : number_format($total_cpc, 2));
			$total_cpa = (!$total_cpa ? 0 : number_format($total_cpa, 2));
			$total_cps = (!$total_cps ? 0 : number_format($total_cps, 2));
			$total_rev = (!$total_rev ? 0 : number_format($total_rev, 2));
			$total_cost = (!$total_cost ? 0 : number_format($total_cost, 2));
			$total_profit = (!$total_profit ? 0 : number_format($total_profit, 2));		
			$total_roi = (!$total_roi ? 0 : number_format($total_roi, 2));
		}

		//display totals row
		if ($preview)
		{
			echo "<tr bgcolor=#FA7F14 >";
			echo '<td class=tbhead2>Total</th>';
			if ($pref['rawclicks'])
				echo "<td class=tbhead2>$total_rawclicks</td>";
			if ($pref['clicks'])
				echo "<td class=tbhead2>$total_clicks</td>";
			if ($pref['actions'])
				echo "<td class=tbhead2>$total_actions</td>";
			if ($pref['sales'])
				echo "<td class=tbhead2>$total_sales</td>";
			if ($pref['cta'])
				echo "<td class=tbhead2>$total_cta%</td>";
			if ($pref['cts'])
				echo "<td class=tbhead2>$total_cts%</td>";
			if ($pref['cpc'])
				echo "<td class=tbhead2>\$$total_cpc</td>";
			if ($pref['cpa'])
				echo "<td class=tbhead2>\$$total_cpa</td>";
			if ($pref['cps'])
				echo "<td class=tbhead2>\$$total_cps</td>";
			if ($pref['cost'])
				echo "<td class=tbhead2>\$$total_cost</td>";
			if ($pref['revenue'])
				echo "<td class=tbhead2>\$$total_rev</td>";
			if ($pref['profit'])
			{
				if ($total_profit < 0)
					echo "<td class=tbhead2><font color=#F51800>\$$total_profit</font></td>";
				else
					echo "<td class=tbhead2><font color=#FFFFFF>\$$total_profit</font></td>";
			}
			if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
			{
				if ($total_roi < 0 ) 
					echo "<td class=tbhead2><font color=#F51800>$total_roi%</font></td>";
				else
					echo "<td class=tbhead2><font color=#FFFFFF>$total_roi%</font></td>";
			}
			if ($pref['column_purpose'])
				echo "<td class=tbhead2>&nbsp;</td>";
			if ($pref['column_group'])
				echo "<td class=tbhead2>&nbsp;</td>";
			if ($pref['description'])
				echo "<td class=tbhead2>&nbsp;</td>";
			echo "</tr>";
		}
		elseif ($export)
		{
			//file open, print this
			//create string for this row
			$b=0;
			if ($pref['rawclicks'])
			{
				$thisrow[$b] = $total_rawclicks;
				$b += 1;
			}
			if ($pref['clicks'])
			{
				$thisrow[$b] = $total_clicks;
				$b += 1;
			}
			if ($pref['actions'])
			{
				$thisrow[$b] = $total_actions;
				$b += 1;
			}			
			if ($pref['sales'])
			{
				$thisrow[$b] = $total_sales;
				$b += 1;
			}
			if ($pref['cta'])
			{
				$thisrow[$b] = $total_cta;
				$b += 1;
			}
			if ($pref['cts'])
			{
				$thisrow[$b] = $total_cts;
				$b += 1;
			}
			if ($pref['cpc'])
			{
				$thisrow[$b] = $total_cpc;
				$b += 1;
			}
			if ($pref['cpa'])
			{
				$thisrow[$b] = $total_cpa;
				$b += 1;
			}
			if ($pref['cps'])
			{
				$thisrow[$b] = $total_cps;
				$b += 1;
			}
			if ($pref['cost'])
						{
				$thisrow[$b] = $total_cost;
				$b += 1;
			}
			if ($pref['revenue'])
			{
				$thisrow[$b] = $total_revenue;
				$b += 1;
			}
			if ($pref['profit'])
			{
				$thisrow[$b] = $total_profit;
				$b += 1;
			}
			if ($pref['roi'])
			{
				$thisrow[$b] = $total_roi;
				$b += 1;
			}
			if ($pref['column_purpose'])
			{
				$thisrow[$b] = "";
				$b += 1;
			}
			if ($pref['column_group'])
			{
				$thisrow[$b] = "";
				$b += 1;
			}
			if ($pref['description'])
			{
				$thisrow[$b] = "";
				$b += 1;
			}

			

			//massage data
			$header = "Totals,";
			for ($i=0;$i<$b;$i++)
			{
				if ($yesquotes)
					$quotes = '"';

				if ($separator == "##")
					$separator = "\t"; //tab

				if ($i == $b-1) //last line, no need for separator
					$header .= $quotes.$thisrow[$i].$quotes;
				else
					$header .= $quotes.$thisrow[$i].$quotes.$separator;

				
			}
			
			$filedata .= $header."\n";
			unset ($thisrow,$header);
		}


	}
	else //no campaigns from filters
		echo "<br><br><table><tr><td>There are no campaigns to display. Please try another group, status or time period.</td></tr>";

	//the end
	echo "</table><br><br>";

	//save to file
	if ($export)
	{		
		if (!$handle2 = @fopen("export.csv", 'w'))
			error("Can't create export.csv.");
		if (@fwrite($handle2, $filedata) === FALSE) 
			error("Can't write to export.csv.");
		fclose($handle2);
	}
}


//FUNCTIONS

function get_campaign_data($type,$campaignID)
{
	global $from_timestamp, $to_timestamp;

	if ($type == "rawclicks")
	{
		//RAWCLICKS
		$rawclickdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'")); 
		return $rawclickdata[0];
	}
	elseif ($type == "clicks")
	{
		//CLICKS
		$clickdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag=1"));
		return $clickdata[0];
	}
	elseif ($type == "actions")
	{
		//CAMPAIGN ACTIONS
		$actiondata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_actions where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $actiondata[0];

	}
	elseif ($type == "sales")
	{
		//CAMPAIGN SALES
		$salesdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_sales where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $salesdata[0];
	}
}

function get_subcampaign_data($type,$campaignID, $subID)
{
	global $from_timestamp, $to_timestamp;

	if ($type == "rawclicks")
	{
		//SUBCAMPAIGN CLICKS
		$sub_rawclicksdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_rawclicksdata[0];
	}
	elseif ($type == "clicks")
	{
		$sub_clicksdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag=1"));
		return $sub_clicksdata[0];
	}
	elseif ($type == "actions")
	{
		//SUBCAMPAIGN ACTIONS
		$sub_actionsdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_actions where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_actionsdata[0];
	}
	elseif ($type == "sales")
	{
		//SUBCAMPAIGN SALES
		$sub_salesdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_sales where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_salesdata[0];
	}
}

require "footer.php";

?>
